package com.lingjtx.common.influx.common;

import org.springframework.core.io.Resource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilderFactory;
import java.util.HashMap;
import java.util.Map;

public class XmlMapperParser {
    public Map<String, InfluxMappedStatement> parse(Resource resource) throws Exception {
        Map<String, InfluxMappedStatement> map = new HashMap<>();
        Document doc = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder().parse(resource.getInputStream());

        String namespace = doc.getDocumentElement().getAttribute("namespace");
        NodeList selects = doc.getElementsByTagName("select");
        for (int i = 0; i < selects.getLength(); i++) {
            Element el = (Element) selects.item(i);
            String id = el.getAttribute("id");
            String sql = el.getTextContent().trim();
            map.put(namespace + "." + id, new InfluxMappedStatement(namespace, id, sql));
        }
        return map;
    }
}